package com.leetcode.partition1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author `RKC`
 * @date 2021/9/10 8:23
 */
public class LC18四数之和 {

    public static List<List<Integer>> fourSum(int[] nums, int target) {
        return doubleIndex(nums, target);
    }

    public static void main(String[] args) {
        int[] nums = {1, -2, -5, -4, -3, 3, 3, 5};
        int target = -11;
        System.out.println(fourSum(nums, target));
    }

    private static List<List<Integer>> doubleIndex(final int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> answers = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            for (int j = i + 1; j < nums.length; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) continue;

                int left = j + 1, right = nums.length - 1;
                while (right > left) {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum > target) right--;
                    else if (sum < target) left++;
                    else {
                        answers.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
                        while (right > left && nums[right] == nums[right - 1]) right--;
                        while (right > left && nums[left] == nums[left + 1]) left++;
                        //找到答案，指针同时收缩
                        right--;
                        left++;
                    }
                }
            }
        }
        return answers;
    }
}
